//important variables
let important = {
    actions: 10,
    colEnd: 4,
    gameOver: false,
    year: 100,
    defense: 0,
    population: 8,
    maxPop: 8,
    nation : 1,
    currentSec : 0,
    pause: false,
    menuOpen: false,
    pauseButton: false,
    timeSpeed : 1,
    timeBase : 15,
    pauseTime : 0,
    resume : 1,
    count : 0
}

const START_YEAR = 100
/*var start = new Date().getTime();
var elapsed = (new Date().getTime() - start) / 1000;

if (elapsed >= 5) {
    endTurn()
}*/


window.onload = function() {
    /*var sec = Math.floor(Date.now()/1000)

    if (sec != important.currentSec) {
        important.currentSec = sec
        console.log(important.currentSec)
    }*/
    //setInterval(endTurn, 10000)
    setInterval(timeCount, 1000)
}

var time = 10
function timeCount() { 
    gatheringTimer()
    switch(important.timeSpeed) {
        case 1 : important.timeBase = 15
                 break
        case 2 : important.timeBase = 7
                 break
        case 3 : important.timeBase = 4
                 break
                 case 0 : important.timeBase = -1
                          time = -1
                          break
    }
    important.timeSpeed == 0 ? important.count = important.count : important.count++
    time--
    if (time == 0) {
        endTurn()
        time = important.timeBase
    }
    console.log(important.timeBase + ' || ' + time + ' || ' + important.count)
}

function gatheringTimer(){
    var fTime = tStart.food + gatherTime.food - important.count
    var waTime = tStart.water + gatherTime.water - important.count
    var woTime = tStart.wood + gatherTime.wood - important.count
    var sTime = tStart.stone + gatherTime.stone - important.count;

    fTime < 0 ? fTime = 0 : fTime = fTime
    waTime < 0 ? waTime = 0 : waTime = waTime
    woTime < 0 ? woTime = 0 : woTime = woTime
    sTime < 0 ? sTime = 0 : sTime = sTime

    document.getElementById('fTimer').innerHTML = '<i>'+ fTime + '</i>'
    document.getElementById('waTimer').innerHTML = '<i>' + waTime + '</i>'
    document.getElementById('woTimer').innerHTML = '<i>' + woTime + '</i>'
    document.getElementById('sTimer').innerHTML = '<i>' + sTime + '</i>'
}

function speedChange(speed) {
    important.timeSpeed = speed
    switch(important.timeSpeed) {
        case 1 : important.timeBase = 15
                 break
        case 2 : important.timeBase = 7
                 break
        case 3 : important.timeBase = 4
                 break
        case 0 : important.timeBase = -1
                 important.pauseTime = time
                 time = -1
                 break
    }
    if (time > important.timeBase) {
        time = important.timeBase
    } else if (time < 0) {
        time = important.pauseTime
    }
}

function pauseButt() {
    if (!important.pause) {
        important.pause = true
        important.pauseButton = true
    } else if (important.pauseButton && important.pause && menuOpen) {
        important.pauseButton = false
    } else if (important.pauseButton && important.pause && !menuOpen) {
        important.pauseButton = false
        important.pause = false
    }

}

// functions for gathering actions
let res = {
    food: 10,
    water: 10,
    wood: 15,
    stone: 0
}
let rates = {
    foodRate: 8,
    waterRate: 10,
    woodRate: 3,
    stoneRate: 3
}

var tStart = {
    food : -3,
    water : -3,
    wood : -3,
    stone : -5
}

var gatherTime = {
    food: 3,
    water : 3,
    wood : 5,
    stone : 7
}

function moreFood() {
    if(important.count > tStart.food + gatherTime.food){
            res.food+=rates.foodRate
            //important.actions--
            console.log(res.food)
            gatheringTimer()
            tStart.food = important.count
    }
    document.getElementById('food').innerHTML = res.food
}

function moreWater() {
    if(important.count > tStart.water + gatherTime.water){
        res.water+=rates.waterRate
        //important.actions--
        console.log(res.water)
        gatheringTimer()
        tStart.water = important.count
    }
    document.getElementById('water').innerHTML = res.water
}

function moreWood() {
    if(important.count > tStart.wood + gatherTime.wood){
        res.wood += rates.woodRate
        //important.actions--
        gatheringTimer()
        tStart.wood = important.count
    }
    document.getElementById('wood').innerHTML = res.wood
}

function moreStone() {
    if (important.count > tStart.stone + gatherTime.stone && builds.quarry > 0 && rates.stoneRate > 0) {
        res.stone += rates.stoneRate
        //important.actions--
        tStart.stone = important.count
        gatheringTimer()
    } else if (builds.quarry <= 0 && important.count > tStart.stone + gatherTime.stone) {
        document.getElementById('warnings').innerHTML = 'You have no quarries!'
    } else if (rates.stoneRate == 0 && important.count > tStart.stone + gatherTime.stone) {
        document.getElementById('warnings').innerHTML = 'You have no miners!'
    }

    document.getElementById('stone').innerHTML = res.stone
}

// building functions

let builds = {
    houses:2,
    farms:1,
    logging:0,
    wallLevel:0,
    quarry:0,
    well:0,
    armory:0,
    tradePost:0
}

let cost = {
    homeCost: 50,
    farmCost: 40,
    logCost: 40,
    wallCost: 45,
    quarryCost: 45,
    wellCost: 20,
    armoryCost: 40,
    tradeCost:50
}

let workTotal = {
    farm: 8,
    wood: 0,
    guard: 0,
    miner: 0,
    soldier: 0
}

function buildHouse() {
    if (res.wood >= cost.homeCost && important.actions > 0) {
        builds.houses++
        important.actions--
        res.wood -= cost.homeCost
        cost.homeCost += Math.floor(cost.homeCost / 10)
        document.getElementById('homes').innerHTML = builds.houses
        document.getElementById('wood').innerHTML = res.wood
        document.getElementById('homeMat').innerHTML = "Required: " + cost.homeCost + " Wood"
        important.maxPop += 4
        document.getElementById('pop').innerHTML = 'Population: ' + important.population + '/' + important.maxPop
    } else if (res.wood < cost.homeCost && important.actions > 0) {
        document.getElementById('warnings').innerHTML = 'Not enough wood!'
    }
}

function buildFarm() {
    if (res.wood >= cost.farmCost && important.actions > 0) {
        builds.farms++
        important.actions--
        res.wood -= cost.farmCost
        workTotal.farm += 4
        cost.farmCost += Math.floor(cost.farmCost / 10)
        document.getElementById('farm').innerHTML = builds.farms
        document.getElementById('wood').innerHTML = res.wood
        document.getElementById('farmMat').innerHTML = "Required: " + cost.farmCost + " Wood"
        document.getElementById('farmerCount').innerHTML = '<i>Farmers: ' + workers.farm + '/' + workTotal.farm + '</i>'
    } else if (res.wood < cost.farmCost && important.actions > 0) {
        document.getElementById('warnings').innerHTML = 'Not enough wood!'
    }
}

function buildLogger() {
    if (res.wood >= cost.logCost && important.actions > 0) {
        builds.logging++
        important.actions--
        res.wood -= cost.logCost
        cost.logCost += Math.floor(cost.logCost/10)
        workTotal.wood += 4
        document.getElementById('logs').innerHTML = builds.logging
        document.getElementById('wood').innerHTML = res.wood
        document.getElementById('logMat').innerHTML = "Required: " + cost.logCost + " Wood"
        document.getElementById('loggerCount').innerHTML = '<i>Loggers: ' + workers.logger + '/' + workTotal.wood + '</i>'
    }
}

function buildWall() {
    if (builds.wallLevel == 0) {
        if (res.wood >= cost.wallCost && important.actions > 0) {
            console.log('build')
            builds.wallLevel++
            res.wood -= cost.wallCost
            important.defense+= 4
            workTotal.guard+=4
            important.actions--
            document.getElementById('wall').innerHTML = 'Wooden Palisade'
            document.getElementById('wood').innerHTML = res.wood
            document.getElementById('guardCount').innerHTML = '<i>Guards: ' + workers.guard +  '/' + workTotal.guard + '</i>'
            document.getElementById('wallMat').innerHTML = 'Required: 32 Stone'
            cost.wallCost = 32
        }
    } else if (builds.wallLevel == 1) {
        if (res.stone >= cost.wallCost && important.actions > 0) {
            builds.wallLevel++
            res.stone -= cost.wallCost
            important.defense+= 4
            workTotal.guard+=4
            important.actions--
            document.getElementById('wall').innerHTML = 'Stone Walls'
            document.getElementById('stone').innerHTML = res.stone
            document.getElementById('guardCount').innerHTML = '<i>Guards: ' + workers.guard +  '/' + workTotal.guard + '</i>'
            document.getElementById('wallMat').innerHTML = 'Required: N/A'
        }
    } else { document.getElementById('warnings').innerHTML = 'No further upgrades!' }
}

function buildQuarry() {
    if (res.wood >= cost.quarryCost && important.actions > 0){
        builds.quarry++
        res.wood -= cost.quarryCost
        workTotal.miner += 4
        important.actions--
        cost.quarryCost += Math.floor(cost.quarryCost/4)
        document.getElementById('quarry').innerHTML = builds.quarry
        document.getElementById('wood').innerHTML = res.wood
        document.getElementById('minerCount').innerHTML = '<i>Miners: ' + workers.miner +  '/' + workTotal.miner + '</i>'
    }

    document.getElementById('hiddenStone').style.display = 'table-cell'
}

function buildWell() {
    if (res.stone >= cost.wellCost && important.actions > 0) {
        builds.well++
        rates.waterRate += 5
        res.stone -= cost.wellCost
        important.actions--
        cost.wellCost += Math.floor(cost.wellCost/2)
        document.getElementById('well').innerHTML = builds.well
        document.getElementById('stone').innerHTML = res.stone
        document.getElementById('wellCost').innerHTML = 'Required: ' + cost.wellCost + ' Stone'
    }
}

function buildArmory() {
    if (res.stone >= cost.armoryCost && important.actions > 0){
        builds.armory++
        important.actions--
        workTotal.soldier+=4;
        cost.armoryCost+=Math.floor(cost.armoryCost/3)
        document.getElementById('armory').innerHTML = builds.armory
        document.getElementById('stone').innerHTML = res.stone
        document.getElementById('soldierCount').innerHTML = '<i>Soldiers: ' + workers.soldiers +  '/' + workTotal.soldier + '</i>'
        document.getElementById('wallMat').innerHTML = 'Required: ' + cost.armoryCost + ' Stone'

        document.getElementById('war').style.display = 'block'
    }
}

function buildTrade() {
    if (res.wood > cost.tradeCost && important.actions > 0 && builds.tradePost == 0) {
        builds.tradePost++
        res.wood -= cost.tradeCost
        important.actions--
        document.getElementById('tradePost').innerHTML = builds.tradePost
        document.getElementById('tradeMat').innerHTML = 'N/A'
        updateResources()
        document.getElementById('trade').style.display = 'block'
    } else if (builds.tradePost == 1) {
        document.getElementById('warnings').innerHTML = 'No more trading posts can be built!'
    }
}

//job shiftings
let workers = {
    pop: 8,
    available: 0,
    farm: 8,
    logger: 0,
    guard:0,
    miner: 0,
    soldiers: 0
}

function addWorker(add, workerType){
    if (workerType == 'farmer') {           //FARMERS
        if (add) {
            if (important.population - workers.pop > 0 && builds.farms > 0 && workers.farm < workTotal.farm) {
                workers.pop++
                rates.foodRate = workers.farm
                workers.farm++
                workers.available = important.population - workers.pop
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
                document.getElementById('farmerCount').innerHTML = '<i>Farmers: ' + workers.farm + '/' + workTotal.farm + '</i>'
                document.getElementById('foodGain').innerHTML = 'You are gaining food at a rate of ' + rates.foodRate +' Food per year.'
                console.log('food | ' + workers.farm + '/' + workTotal.farm)
            } else if (workers.available <=0) { document.getElementById('warnings').innerHTML = 'Not enough available workers!' } 
            else if (builds.farms == 0) { document.getElementById('warnings').innerHTML = 'There are no farms!' }
            else if (workers.farm >= workTotal.wood) { document.getElementById('warnings').innerHTML = 'There\'s no space left in the farms!' }
        } else if (!add) {
            if (workers.farm > 0) {
                workers.pop--
                rates.foodRate--
                workers.farm--
                rates.foodRate = workers.farm
                workers.available = important.population - workers.pop
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
                document.getElementById('farmerCount').innerHTML = '<i>Farmers: ' + workers.farm + '/' + workTotal.farm + '</i>'
                document.getElementById('foodGain').innerHTML = 'You are gaining food at a rate of ' + rates.foodRate +' Food per year.'
            } else { document.getElementById('warnings').innerHTML = 'There are no more farmers!' }
        }
    }
    if (workerType == 'logger') {          //LOGGERS
        if (add) {
            if (important.population - workers.pop > 0 && builds.logging > 0 && workers.logger < workTotal.wood) {
                workers.pop++
                rates.woodRate++
                workers.logger++
                workers.available = important.population - workers.pop
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
                document.getElementById('loggerCount').innerHTML = '<i>Workers: ' + workers.logger + '/' + workTotal.wood + '</i>'
                console.log(rates.woodRate)
                console.log('wood | ' + workers.logger + '/' + workTotal.wood)
            } else if (workers.available <= 0) { document.getElementById('warnings').innerHTML = 'Not enough available workers!' }
            else if (builds.logging == 0) { document.getElementById('warnings').innerHTML = 'There are no logging camps!' }
            else if (workers.logger >= workTotal.wood) { document.getElementById('warnings').innerHTML = 'There\'s no space left in the logging camps!' }
        } else if (!add) {
            if (workers.logger > 0) {
                workers.pop--
                rates.woodRate--
                workers.logger--
                workers.available = important.population - workers.pop
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
                document.getElementById('loggerCount').innerHTML = '<i>Workers: ' + workers.logger +  '/' + workTotal.wood + '</i>'
                console.log(rates.woodRate)
            } else { document.getElementById('warnings').innerHTML = 'There are no more loggers!' }
        }
    }
    if (workerType == 'guard') {           //GUARDS
        if (add) {
            if (important.population - workers.pop > 0 && builds.wallLevel > 0 && workers.guard < workTotal.guard) {
                workers.pop++
                important.defense++
                workers.guard++
                workers.available = important.population - workers.pop
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
                document.getElementById('guardCount').innerHTML = '<i>Guards: ' + workers.guard + '/' + workTotal.guard + '</i>'
            } else if (workers.available <= 0) { document.getElementById('warnings').innerHTML = 'Not enough available workers!' }
            else if (builds.wallLevel == 0) { document.getElementById('warnings').innerHTML = 'You have no wall!' }
            else if (workers.guard >= workTotal.guard) { document.getElementById('warnings').innerHTML = 'There\'s no space left on the wall!' }
        } else if (!add) {
            if (workers.guard > 0) {
                workers.pop--
                important.defense--
                workers.guard--
                workers.available = important.population - workers.pop
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
                document.getElementById('guardCount').innerHTML = '<i>Guards: ' + workers.guard +  '/' + workTotal.guard + '</i>'
                console.log(rates.woodRate)
            } else { document.getElementById('warnings').innerHTML = 'There are no more guards!' }
        }
    }
    if (workerType == 'miner') {
        if (add) {
            if (important.population - workers.pop > 0 && builds.quarry > 0 && workers.miner < workTotal.miner) {
                workers.pop++
                rates.stoneRate++
                workers.miner++
                workers.available = important.population - workers.pop
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
                document.getElementById('minerCount').innerHTML = '<i>Miners: ' + workers.miner + '/' + workTotal.miner + '</i>'
            } else if (workers.available <= 0) { document.getElementById('warnings').innerHTML = 'Not enough available workers!' }
            else if (builds.quarry == 0) { document.getElementById('warnings').innerHTML = 'You have no quarries!' }
            else if (workers.guard >= workTotal.guard) { document.getElementById('warnings').innerHTML = 'There\'s no space left in the quarries!' }
        } else if (!add) {
            if (workers.miner > 0) {
                workers.pop--
                rates.stoneRate--
                workers.miner--
                workers.available = important.population - workers.pop
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
                document.getElementById('minerCount').innerHTML = '<i>Miners: ' + workers.miner +  '/' + workTotal.miner + '</i>'
            } else { document.getElementById('warnings').innerHTML = 'There are no more miners!' }
        }
    }
    if (workerType == 'soldier') {
        if (add) {
            if (important.population - workers.pop > 0 && builds.armory > 0 && workers.soldiers < workTotal.soldier) {
                workers.pop++
                workers.soldiers++
                workers.available = important.population - workers.pop
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
                document.getElementById('soldierCount').innerHTML = '<i>Soldiers: ' + workers.soldiers + '/' + workTotal.soldier + '</i>'
            } else if (workers.available <= 0) { document.getElementById('warnings').innerHTML = 'Not enough available workers!' }
            else if (builds.quarry == 0) { document.getElementById('warnings').innerHTML = 'You have no armories!' }
            else if (workers.guard >= workTotal.guard) { document.getElementById('warnings').innerHTML = 'There\'s no space left in the barracks!' }
        } else if (!add) {
            if (workers.soldiers > 0) {
                workers.pop--
                workers.soldiers--
                workers.available = important.population - workers.pop
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
                document.getElementById('soldierCount').innerHTML = '<i>Soldiers: ' + workers.soldiers +  '/' + workTotal.soldier + '</i>'
            } else { document.getElementById('warnings').innerHTML = 'There are no more soldiers!' }
        }
    }
}

//COMBAT
function combat(offensive, enemyStr, tribeStr){
    if (!offensive) {
        if (enemyStr <= tribeStr) {
            return  true
        } else { return false}
    } if (offensive) {
        let winChance = 0
        if (tribeStr >= enemyStr) {
            winChance = Math.ceil(Math.random() * 10)
            if (winChance >= 3) {
                return true
            } else { return false }
        } else if (tribeStr < enemyStr) {
            if (winChance >= 7) {
                return true
            } else { return false }
        }
    }
}

function raid() {
    otherTribeStr = Math.ceil(Math.random() * (2-10) + 10)
    victory = combat(true, otherTribeStr, workers.soldiers)

    if (victory) {
        resourcesLost = 0
        resourceType = ''

        resourceTypeGain = Math.floor(Math.random() * 4)
        if (resourceTypeGain <=1) {
            resourceType = 'Wood'
            tempWood = res.wood
            res.wood += Math.floor(Math.random() * 50)
            resourcesLost = res.wood - tempWood
        } else if (resourceTypeGain <= 2) {
            resourceType = 'Food'
            tempFood = res.food
            res.food += Math.floor(Math.random() * 50)
            resourcesLost = res.food - tempFood
        } else if (resourceTypeGain <= 3) {
            resourceType = 'Water'
            tempWater = res.water
            res.water += Math.floor(Math.random() * 50)
            resourcesLost = res.water - tempWater
        } else if (resourceTypeGain <= 4) {
            resourceType = 'Stone'
            tempStone = res.stone
            res.stone += Math.floor(Math.random() * 50)
            resourcesLost = res.stone - tempStone
        }

        updateResources()

        document.getElementById('warnings').innerHTML = 'You won the battle!<br>Enemy strength: ' + otherTribeStr + ' | Your strength: ' + workers.soldiers + '<br>You gained: ' + resourcesLost + ' ' + resourceType
    } else if (!victory){
        document.getElementById('warnings').innerHTML = 'You lost the battle!<br>Enemy strength: ' + otherTribeStr + ' | Your strength: ' + workers.soldiers
    }
}

let tribes = {
    1 : {name:'Tolsta', str:6},
    2 : {name:'Lavoya', str:12},
    3 : {name:'Alveyit', str: 15}
}

function conquer() {
    important.nation++
    victory = combat(true, tribes[important.nation].str, workers.soldiers)
    if (victory) {
        document.getElementById('warnings').innerHTML = 'win'
    } else if (!victory) {
        document.getElementById('warnings').innerHTML = 'lose'
    }
}

//show info box
function showInfo(show, type){
    let infoSent = ' '
    if (type != undefined) {
        switch(type) {
            case 'food' :
                infoSent = 'Send people to gather food.<br>Food gained: ' + rates.foodRate
                break
            case 'water' :
                infoSent = 'Have people collet water from the river.<br>Water gained: ' + rates.waterRate
                break
            case 'wood' :
                infoSent = 'Send people to gather wood.<br>Wood gained: ' + rates.woodRate
                break
            case 'stone' :
                infoSent = 'Send people to mine stone.<br>Stone gained: ' + rates.stoneRate
                break
            case 'farm' :
                infoSent = 'Build a farm.<br>Increases maximum number of farmers by 4.'
                break
            case'log' :
                infoSent = 'Build a logging camp.<br>Increases maximum number of loggers by 4.'
                break
            case 'quarry' :
                infoSent = 'Build a quarry.<br>Allows stone mining.'
                break
            case 'wall' :
                infoSent = 'Build a wall around the tribe.<br>Increases defense by 4.<br>Increases maximum number of guards by 4.'
                break
            case 'armory' :
                infoSent = 'Build an armory in the tribe.<br>Allows you to go to war.'
                break
            case 'trade' :
                infoSent = 'Build a trading post outside the tribe.<br>Allows you to trade with your neighbors.'
                break
            case 'well' :
                infoSent = 'Build a well in the tribe.<br>Increases water gain rate by 5.'
                break
            case 'endyr' :
                infoSent = 'End the year and go into the next.'
                break
            case 'home':
                infoSent = 'Build a home in the tribe.<br>Population max +4.'
                break
            case type == 'raid' :
                infoSent = 'Send your soldiers out on a raid.'
                break
            case 'war' :
                if (tribes.nation != 4) {
                     infoSent = 'Send your soliders to conquer a nearby region.<br>Current closest tribe: ' + tribes[important.nation].name
                } else {
                    infoSent = 'Send your soliders to conquer a nearby region.<br>There are no nearby tribes to conquer.'
                }
                break
        }
    }

    if (show) {
        document.getElementById('itemInformation').innerHTML = infoSent
        document.getElementById('info').style.display = 'block'
    } else if(!show) {
        document.getElementById('info').style.display = 'none'
    }
}

function showMenu() {
    if (document.getElementById('fullMenu').style.display != 'block') {
        document.getElementById('fullMenu').style.display = 'block'
        important.resume = important.timeSpeed
        speedChange(0)
    } else if (document.getElementById('fullMenu').style.display == 'block') {
        document.getElementById('fullMenu').style.display = 'none'
        speedChange(important.resume)
    }
}

// end previous turn, start next turn
let waterSurplus = false
let foodSurplus = false
let foodDeficit = false

conquered = false

function updateResources() {
    document.getElementById('food').innerHTML = res.food
    document.getElementById('water').innerHTML = res.water
    document.getElementById('wood').innerHTML = res.wood
    document.getElementById('stone').innerHTML = res.stone
    builds.quarry >= 1 ? document.getElementById('hiddenStone').style.display = 'table-cell' : document.getElementById('hiddenStone').style.display = 'none'
    document.getElementById('pop').innerHTML = 'Population: ' + important.population + '/' + important.maxPop
    console.log('Resources updated')
}

function updateAllText() {
    document.getElementById('year').innerHTML = 'Year: ' + important.year
    console.log(important.year)
    document.getElementById('actions').innerHTML = actions
    updateResources()
    document.getElementById('farm').innerHTML = builds.farms
    document.getElementById('wood').innerHTML = res.wood
    document.getElementById('farmerCount').innerHTML = '<i>Farmers: ' + workers.farm + '/' + workTotal.farm + '</i>'
    document.getElementById('logs').innerHTML = builds.logging
    document.getElementById('logMat').innerHTML = "Required: " + cost.logCost + " Wood"
    document.getElementById('loggerCount').innerHTML = '<i>Loggers: ' + workers.logger + '/' + workTotal.wood + '</i>'
    if (builds.wallLevel == 1) { 
        document.getElementById('wall').innerHTML = 'Wooden Palisade'
        document.getElementById('guardCount').innerHTML = '<i>Guards: ' + workers.guard +  '/' + workTotal.guard + '</i>'
        document.getElementById('wallMat').innerHTML = 'Required: 32 Stone'
    } else if (builds.wallLevel == 2) {
        document.getElementById('wall').innerHTML = 'Stone Walls'
        document.getElementById('guardCount').innerHTML = '<i>Guards: ' + workers.guard +  '/' + workTotal.guard + '</i>'
        document.getElementById('wallMat').innerHTML = 'Required: N/A'
    }
    document.getElementById('quarry').innerHTML = builds.quarry
    document.getElementById('minerCount').innerHTML = '<i>Miners: ' + workers.miner +  '/' + workTotal.miner + '</i>'
    document.getElementById('homes').innerHTML = builds.houses
    document.getElementById('homeMat').innerHTML = "Required: " + cost.homeCost + " Wood"
    document.getElementById('pop').innerHTML = 'Population: ' + important.population + '/' + important.maxPop
    document.getElementById('well').innerHTML = builds.well
    document.getElementById('wellCost').innerHTML = 'Required: ' + cost.wellCost + ' Stone'
    document.getElementById('armory').innerHTML = builds.armory
    document.getElementById('soldierCount').innerHTML = '<i>Soldiers: ' + workers.soldiers +  '/' + workTotal.soldier + '</i>'
    document.getElementById('wallMat').innerHTML = 'Required: ' + cost.armoryCost + ' Stone'
    builds.armory >= 1 ? document.getElementById('war').style.display = 'block' : document.getElementById('war').style.display = 'none'
    document.getElementById('tradePost').innerHTML = builds.tradePost
    document.getElementById('tradeMat').innerHTML = 'N/A'
    builds.tradePost >= 1 ? document.getElementById('trade').style.display = 'block' : document.getElementById('trade').style.display = 'none'
}

function endTurn(){
    /*if (important.actions > 0) {
        document.getElementById('warnings').innerHTML = 'You still have remaining actions!'
        return
    } 

    if (workers.available < 0) {
        document.getElementById('warnings').innerHTML = 'You must reassign some workers!'
        return
    }*/

    if (!important.gameOver && !important.pause) {
        res.food > 0 ? res.food-=important.population : res.food = 0
        res.water > 0 ? res.water-=important.population : res.water = 0
        waterSurplus ? res.water += important.population : res.water = res.water
        foodSurplus ? res.food += important.population : res.food = res.food
        foodDeficit ? res.food -= Math.floor(important.population / 2) : res.food = res.food
        document.getElementById('warnings').innerHTML = ' '
        if (res.water <= 0 || res.food <= 0) {
            important.colEnd--
            document.getElementById('warnings').innerHTML = 'Your tribe has ' + important.colEnd + ' years remaining!'
            if (res.water < 0) {
                res.water = 0
                document.getElementById('water').innerHTML = res.water
            }
            if (res.food < 0) {
                res.food = 0
                document.getElementById('food').innerHTML = res.food
            }
        } else if (res.water > 0 && res.food > 0){
            important.colEnd = 3
        }
        important.year++
        document.getElementById('year').innerHTML = 'Year: ' + important.year

        if (important.maxPop - important.population != 0 && important.population != 1) {
            var popAddChance = Math.floor(Math.random() * 100)
            if (popAddChance >= 60) {
                important.population++
                workers.available = important.population - workers.pop
                document.getElementById('pop').innerHTML = 'Population: ' + important.population + '/' + important.maxPop
                document.getElementById('warnings').innerHTML = 'A child has been born in the tribe!'
                document.getElementById('unusedPop').innerHTML = 'Available Workers: ' + workers.available + '/' + important.population
            }
        }

        randEventPick = Math.floor(Math.random() * 100)
        //console.log(randEventPick)

        if (randEventPick >= 70 && randEventPick <80) {
            raiders()
        } else if(randEventPick >= 80 && randEventPick < 85) {
            badHarvest()
        } else if (randEventPick >= 85 && randEventPick <96) {
            goodHarvest()
        } else if (randEventPick >= 96) {
            heavyRains()
        } else {
            waterSurplus = false
            foodSurplus = false
            foodDeficit = false
        }
    }

    if (important.colEnd >= 1) { important.actions = 10 }
    updateResources()
    if (important.colEnd <= 0) {
        if (!conquered) {
            document.getElementById('warnings').innerHTML = 'Game over!<br>Your tribe lasted ' + (important.year - START_YEAR) + ' years'
            important.gameOver = true
        } else if(conquered) {
            document.getElementById('warnings').innerHTML = 'Your tribe was conquered!<br>Your tribe lasted ' + (important.year - START_YEAR) + ' years'
            important.gameOver = true
        }
    }
}

function heavyRains() {
    document.getElementById('warnings').innerHTML = 'The tribe faces heavy rains.'
    waterSurplus = true
} 
function goodHarvest() {
    document.getElementById('warnings').innerHTML = 'The tribe is having a very good harvest!'
    foodSurplus = true
}
function badHarvest() {
    document.getElementById('warnings').innerHTML = 'Your tribe suffers a bad harvest!'
    foodDeficit = true
}
function raiders() {
    raiderStr = Math.floor(Math.random() * (8-3) + 3)
    victory = combat(false, raiderStr, important.defense)
    console.log('attack')
    resourcesLost = 0
    resourceType = ''

    if (victory) {
        document.getElementById('warnings').innerHTML = 'Your tribe was attacked, but the raiders were repelled!\nRaider strength: ' + raiderStr + ' | Your strength: ' + important.defense
    } else if (!victory) {
        popLost = Math.ceil(Math.random() * (important.population/2))
        important.population-=popLost
        if (important.population <= 1) {
            important.population = 0
            important.gameOver = true
            important.colEnd = 0
            updateResources()
            conquered = true
            endTurn()
        }
        resourceTypeLost = Math.floor(Math.random() * 4)
        if (resourceTypeLost <=1) {
            resourceType = 'Wood'
            tempWood = res.wood
            res.wood -= Math.floor(Math.random() * (res.wood/2))
            resourcesLost = tempWood - res.wood
        } else if (resourceTypeLost <= 2) {
            resourceType = 'Food'
            tempFood = res.food
            res.food -= Math.floor(Math.random() * (res.food/2))
            resourcesLost = tempFood - res.food
        } else if (resourceTypeLost <= 3) {
            resourceType = 'Water'
            tempWater = res.water
            res.water -= Math.floor(Math.random() * (res.water/2))
            resourcesLost = tempWater - res.water
        } else if (resourceTypeLost <= 4) {
            resourceType = 'Stone'
            tempStone = res.stone
            res.stone -= Math.floor(Math.random() * (res.stone/4))
            resourcesLost = tempStone - res.stone
        }
        document.getElementById('warnings').innerHTML = 'Your tribe was attacked, and your defenses fell!<br>Raider strength: ' + raiderStr + ' | Your strength: ' + important.defense + ' <br>Population lost: ' + popLost + ' | Resources lost: ' + resourcesLost + ' ' + resourceType
        updateResources()
    }
}

//setTimeout(endTurn(), 5000)

//SAVE/LOAD GAME
function saveGame() {
    localStorage.setItem('main', JSON.stringify(important));
    localStorage.setItem('resources', JSON.stringify(res));
    localStorage.setItem('rates', JSON.stringify(rates));
    localStorage.setItem('workers', JSON.stringify(workers));
    localStorage.setItem('work totals', JSON.stringify(workTotal));
    localStorage.setItem('builds', JSON.stringify(builds));
    localStorage.setItem('costs', JSON.stringify(cost));
    localStorage.setItem('tribes', JSON.stringify(tribes))

    console.log('Saved!')
    document.getElementById('warnings').innerHTML = 'Saved game!'
}

function loadGame() {
    important = JSON.parse(localStorage.getItem('main'))
    res = JSON.parse(localStorage.getItem('resources'))
    rates = JSON.parse(localStorage.getItem('rates'))
    workers = JSON.parse(localStorage.getItem('workers'))
    workTotal = JSON.parse(localStorage.getItem('work totals'))
    builds = JSON.parse(localStorage.getItem('builds'))
    cost = JSON.parse(localStorage.getItem('costs'))
    tribes = JSON.parse(localStorage.getItem('tribes'))
    
    console.log('Loaded game!')
    document.getElementById('warnings').innerHTML = 'Loaded!'
    updateAllText();
}

function devMode() {            //FOR EASE OF DEVELOPMENT ONLY
    res.wood = 1000000
    res.water = 1000000
    res.food = 1000000
    res.stone = 1000000
    updateResources()
    document.getElementById('hiddenStone').style.display = 'table-cell'     //call thru inspector console
}

//LINKS
//<a target="_blank" href="https://icons8.com/icons/set/play">Play icon</a> icon by <a target="_blank" href="https://icons8.com">Icons8</a>
